<?php
/**
 * User controller
 */
class UserController extends Zend_Controller_Action
{
    /**
     * UserPage Action
     */
    public function indexAction()
    {

    }

    /**
     * Login action
     */
    public function loginAction()
    {
        $params = $this->_request->getParams();

        if ($this->_request->isPost()) {
            $error = array();

            if (!$this->_isValid($params['user_name'], array('notEmpty' => true))) {
                $error['user_name'] = "Username must not be empty";
            }

            if (!$this->_isValid($params['user_pass'], array('notEmpty' => true))) {
                $error['user_pass'] = "Password must not be empty";
            }

            if ($error) {
                $arrError = array('error_code' => -1, 'error_msg' => $error, 'data' => null);
                $this->_helper->json($arrError);
            }

            $intUserID = Plun_Model_User::checkUserLogin(array('user_name' => trim($params['user_name']), 'user_pass' => trim($params['user_pass'])));

            if (empty($intUserID)) {
                $arrError = array('error_code' => -1, 'error_msg' => array('message' => 'Username or password is not correct'), 'data' => null);
                $this->_helper->json($arrError);
            }

            $arrUserInfo = Plun_Model_User::getUserInfo($intUserID);

//            if (!(($arrUserInfo['user_status'] & 4) == 4) && 0) {
//                $arrError = array('error_code' => -1, 'error_msg' => array('message' => 'Tài khoản chưa được kích hoạt. Để hoàn tất đăng ký, vui lòng vào ' + $params['username'] + ' để kích hoạt tài khoản.'), 'data' => null);
//                $this->_helper->json($arrError);
//            }

            $identity = array(
                'user_id' => $arrUserInfo['user_id'],
                'user_name' => $arrUserInfo['user_name'],
                'user_email' => $arrUserInfo['user_email'],
                'user_role' => $arrUserInfo['user_role']
            );

            Zend_Auth::getInstance()->getStorage()->write($identity);

            $arrData = array(
                'error_code' => 0,
                'error_msg' => 'success',
                'data' => array('user_id' => $identity['user_id'], 'user_name' => $identity['user_name'])
            );

            //$this->_helper->json($arrData);
            $this->_redirect('user');
        }
    }

    /**
     * Logout action
     */
    public function logoutAction()
    {
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender();

        $auth = Zend_Auth::getInstance();

        if ($auth->getIdentity()) {
            $auth->clearIdentity();
            Plun_Session::destroy();
        }
        $this->_redirect('/#/login');
    }

    /**
     * User sign up action
     */
    public function signupAction()
    {
        if ($this->_request->isPost()) {
            //Get params
            $params = $this->_request->getPost();

            //Check valid
            $userParams = array(
                "user_name" => $params['user_name'],
                "user_email" => $params['user_email'],
                "user_pass" => md5($params['user_pass']),
                "user_age" => $params['user_age'],
                "user_height" => $params['user_height'],
                "user_weight" => $params['user_weight'],
                "user_role" => $params['user_role'],
                "country_id" => $params['country_id'],
                "location_id" => $params['location_id'],
                "district_id" => $params['district_id'],
                "about_me" => $params['about_me'],
                "ip" => $this->getRequest()->getClientIp(),
                "create_date" => time()
            );

            //var_dump($userParams); exit;

            //Insert to db
            $result = Plun_Model_User::insertUserInfo($userParams);

            if ($result) {
                $this->redirect('user/login');
            }
        }
    }

    /**
     * Check params valid
     * @param $strParam
     * @param $arrType
     * @return bool
     */
    private function _isValid($strParam, $arrType)
    {
        switch ($arrType) {
            case $arrType['notEmpty']:
                $validator = new Zend_Validate();
                $validator->addValidator(new Zend_Validate_StringLength(array('max' => 255, 'encoding' => 'UTF-8')))
                    ->addValidator(new Zend_Validate_NotEmpty());
                return $validator->isValid($strParam);
                break;
            case $arrType['email']:
                $validator = new Zend_Validate();
                $validator->addValidator(new Zend_Validate_StringLength(array('max' => 255)));
                $validator->addValidator(new Zend_Validate_EmailAddress());
                $validator->addValidator(new Zend_Validate_NotEmpty());
                return $validator->isValid($strParam);
                break;
            case $arrType['password']:
                $validator = new Zend_Validate();
                $validator->addValidator(new Zend_Validate_StringLength(array('min' => 6, 'max' => 32, 'encoding' => 'UTF-8')))
                    ->addValidator(new Zend_Validate_NotEmpty());
                return $validator->isValid($strParam);
                break;
        }
    }

}